/**
 * 工时查询表单组件
 */

'use client';

import React from 'react';
import {
  Form,
  Input,
  Select,
  DatePicker,
  Button,
  Space,
  Card,
  Row,
  Col,
  Tag,
} from 'antd';
import {
  SearchOutlined,
  ClearOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import type { WorkloadQueryParams } from '../types/workload';
import { useWorkloadMeta } from '../hooks/useWorkloads';

const { Option } = Select;
const { RangePicker } = DatePicker;

interface WorkloadQueryFormProps {
  onSearch: (params: WorkloadQueryParams) => void;
  loading?: boolean;
  initialValues?: WorkloadQueryParams;
}

export default function WorkloadQueryForm({
  onSearch,
  loading = false,
  initialValues,
}: WorkloadQueryFormProps) {
  const [form] = Form.useForm();
  const { workloadTypes, users, projects, loading: metaLoading } = useWorkloadMeta();

  const handleSearch = () => {
    const values = form.getFieldsValue();
    console.log('工时查询表单原始值:', values);
    
    // 处理日期范围
    const params: WorkloadQueryParams = { ...values };
    
    if (values.dateRange) {
      params.start_at = values.dateRange[0]?.startOf('day').unix();
      params.end_at = values.dateRange[1]?.endOf('day').unix();
      delete params.dateRange;
    }

    // 移除空值
    Object.keys(params).forEach(key => {
      const value = params[key as keyof WorkloadQueryParams];
      if (value === undefined || value === null || value === '') {
        delete params[key as keyof WorkloadQueryParams];
      }
    });

    // 处理分页参数
    if (params.page_size === 'all' || !params.page_size) {
      // 获取所有数据，删除分页参数
      delete params.page_index;
      delete params.page_size;
    } else {
      // 使用分页，确保从第一页开始
      params.page_index = 0;
      params.page_size = Number(params.page_size);
    }

    console.log('工时查询最终参数:', params);
    onSearch(params);
  };

  const handleReset = () => {
    form.resetFields();
    // 重置时获取所有数据，不设置分页参数
    onSearch({});
  };

  const getPrincipalTypeTag = (type: string) => {
    const typeMap: Record<string, { color: string; text: string }> = {
      idea: { color: 'purple', text: '需求' },
      work_item: { color: 'blue', text: '工作项' },
      test_case: { color: 'green', text: '测试用例' },
    };
    const config = typeMap[type] || { color: 'default', text: type };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  return (
    <Card 
      title={
        <Space>
          <span>工时查询条件</span>
          {metaLoading && <span style={{ fontSize: '12px', color: '#999' }}>加载项目数据中...</span>}
          {!metaLoading && projects.length > 0 && (
            <span style={{ fontSize: '12px', color: '#52c41a' }}>
              已加载 {projects.length} 个项目，{users.length} 个用户
            </span>
          )}
        </Space>
      }
      size="small"
      styles={{ body: { paddingBottom: 8 } }}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={initialValues}
        onFinish={handleSearch}
      >
        <Row gutter={[12, 8]}>
          {/* 第一行：主要查询条件 */}
          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="工时主体类型" name="principal_type" style={{ marginBottom: 8 }}>
              <Select placeholder="选择主体类型" allowClear size="small">
                <Option value="idea">
                  {getPrincipalTypeTag('idea')} 需求
                </Option>
                <Option value="work_item">
                  {getPrincipalTypeTag('work_item')} 工作项
                </Option>
                <Option value="test_case">
                  {getPrincipalTypeTag('test_case')} 测试用例
                </Option>
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item 
              label={`项目/产品 ${projects.length > 0 ? `(共${projects.length}个)` : ''}`} 
              name="pilot_id" 
              style={{ marginBottom: 8 }}
            >
              <Select
                placeholder={projects.length === 0 ? "加载项目中..." : "选择项目"}
                allowClear
                showSearch
                size="small"
                loading={projects.length === 0}
                optionFilterProp="children"
                filterOption={(input, option) =>
                  String(option?.label || option?.children || '').toLowerCase().includes(input.toLowerCase())
                }
                notFoundContent={projects.length === 0 ? "加载中..." : "未找到匹配项目"}
              >
                {projects.map(project => (
                  <Option key={project.id} value={project.id} label={`${project.name} (${project.identifier})`}>
                    {project.name} ({project.identifier})
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="工时主体ID" name="principal_id" style={{ marginBottom: 8 }}>
              <Input placeholder="工时主体ID" allowClear size="small" />
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={8} lg={5}>
            <Form.Item label="登记日期范围" name="dateRange" style={{ marginBottom: 8 }}>
              <RangePicker
                format="YYYY-MM-DD"
                placeholder={['开始日期', '结束日期']}
                size="small"
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="登记人" name="report_by_id" style={{ marginBottom: 8 }}>
              <Select
                placeholder="选择登记人"
                allowClear
                showSearch
                size="small"
                optionFilterProp="children"
                filterOption={(input, option) => {
                  const children = String(option?.label || option?.children || '');
                  return children.toLowerCase().includes(input.toLowerCase());
                }}
              >
                {users.map(user => (
                  <Option key={user.id} value={user.id}>
                    {user.display_name} ({user.name})
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={3}>
            <Form.Item label="每页显示" name="page_size" initialValue="all" style={{ marginBottom: 8 }}>
              <Select placeholder="每页数量" size="small">
                <Option value="all">全部</Option>
                <Option value={10}>10条</Option>
                <Option value={20}>20条</Option>
                <Option value={30}>30条</Option>
                <Option value={50}>50条</Option>
                <Option value={100}>100条</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row style={{ marginTop: 8 }}>
          <Col span={24}>
            <Space>
              <Button
                type="primary"
                icon={<SearchOutlined />}
                onClick={handleSearch}
                loading={loading}
                size="small"
              >
                查询
              </Button>
              <Button
                icon={<ClearOutlined />}
                onClick={handleReset}
                size="small"
              >
                重置
              </Button>
            </Space>
          </Col>
        </Row>
      </Form>
    </Card>
  );
}